package com.util_code.okhttp.transformer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Response;

public class FileTransformer implements HttpTransformer<File> {

    private String destFileDir;
    private String destFileName;

    public FileTransformer(String filefold, String filename) {
        destFileDir = filefold;
        destFileName = filename;
    }

    @Override
    public File transform(Response response) throws IOException {
        return saveFile(response);
    }

    private File saveFile(Response response) throws IOException {
        File dir = new File(destFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, destFileName);
        if (file.exists()) {
            file.delete();
        }

        InputStream is = null;
        byte[] buf = new byte[4096];
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            long total = response.body().contentLength();
            long sum = 0;
            int len = 0;
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
            }
            fos.flush();
            return file;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
